﻿using System;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using System.Windows;
using Comm.HardDisk;
using Comm.Security;
using SmartMeterParamFrame;
using SmartMeterParamSetting.SchemesServer;

namespace SmartMeterParamSetting
{
    /// <summary>
    ///     App.xaml 的交互逻辑
    /// </summary>
    public partial class App 
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                Mod_Main.systemInfo.Load();
                ClientLicense license = ClientLicense.Load();
                if (license == null || !license.IsAuthorized(HardDiskHelper.GetAllHardDiskSN()))
                {
                    Mod_Main.IsLicense = false;
                }
                //如果 加载失败，则尝试从网络申请
                if (Mod_Main.IsLicense == false)
                {
                    string[] sns = HardDiskHelper.GetAllHardDiskSN()
                                                 .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
                    if (sns.Length < 1)
                    {
                        MessageBox.Show("无法获取硬盘或网卡序列号");
                    }
                    else
                    {
                        var client = new SchemesServerClient();
                        client.Endpoint.Address = new EndpointAddress(Mod_Main.systemInfo.FaServer);
                        byte[] data = client.GetClientLicense(HardDiskHelper.GetAllHardDiskSN().Split(',')[0].Trim());

                        if (data != null && data.Length > 0)
                        {
                            File.WriteAllBytes(string.Format(@"{0}\Clicense.dat", Environment.CurrentDirectory), data);
                            license = ClientLicense.Load();
                            if (license == null || !license.IsAuthorized(HardDiskHelper.GetAllHardDiskSN()))
                            {
                                Mod_Main.IsLicense = false;
                            }
                            else
                            {
                                Mod_Main.IsLicense = true;
                            }
                        }
                        else
                        {
                            MessageBox.Show("无法从方案管理服务器请求许可证文件:\r\n" + Mod_Main.systemInfo.FaServer);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "加载许可证文件失败");
                Mod_Main.IsLicense = false;
            }
            if (e.Args.Length > 0)
            {
                foreach (string s in e.Args)
                {
                    if (s.ToLower() == "-debug") //如果要打印DEBUG信息，则需要重新创建Debug目录，每次启动都会自动清除内容，再创建
                    {
                        MeterControl.IsPrintDebug = true;

                        string path = string.Format(@"{0}\{1}", Environment.CurrentDirectory,
                                                    MeterControl.CONST_DEBUGPATH);
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        Directory.CreateDirectory(path);
                    }

                    if (s.ToLower() == "-asyn")
                    {
                        MeterControl.IsAsynchronous = true;
                    }
                }
            }
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string msg = e.ExceptionObject.ToString();

            MessageBox.Show(msg, "未处理错误");
            if (e.IsTerminating)
                Process.GetCurrentProcess().Kill();
        }
    }
}